<template>
  <div id="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button
        type="primary"
        style="float:left;marginBottom:20px"
        @click="addDialogVisible = true"
        >添加角色</el-button
      >
      <el-table :data="rolesData" style="width: 100%" border stripe>
        <el-table-column type="expand" style="width: 80px">
          <template slot-scope="scope">
            <el-row v-for="one in scope.row.children" :key="one.id">
              <el-col :span="4">
                <el-tag
                  effect="dark"
                  closable
                  @close="handleClose(scope.row, one.id)"
                  >{{ one.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="20">
                <el-row v-for="two in one.children" :key="two.id">
                  <el-col :span="5">
                    <el-tag
                      effect="dark"
                      type="success"
                      closable
                      @close="handleClose(scope.row, two.id)"
                      >{{ two.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-tag
                      effect="dark"
                      type="warning"
                      v-for="three in two.children"
                      :key="three.id"
                      closable
                      @close="handleClose(scope.row, three.id)"
                      >{{ three.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" width="50"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="findEditId(scope.row.id)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="del(scope.row.id)"
            />
            <el-button
              type="warning"
              icon="el-icon-setting"
              circle
              @click="addRights(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      @close="addVisibleClose"
    >
      <el-form
        :model="addForm"
        label-width="80px"
        :rules="addRules"
        ref="addForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSure">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible">
      <el-form
        :model="editForm"
        label-width="80px"
        :rules="addRules"
        ref="editForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSure">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="addRightsDialogVisible">
      <el-tree
        :data="treeData"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        :props="treeProps"
        @click="closeAddRightsDialog"
        ref="treeRef"
      >
      </el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRightsSure">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import "@/assets/css/roles/roles.scss";

export default {
  data() {
    return {
      rolesData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addRightsDialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      editForm: {
        roleName: "",
        roleDesc: "",
      },
      addRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      treeData: [],
      treeProps: {
        children: "children",
        label: "authName",
      },
      defKeys: [],
      roleId: "",
    };
  },
  created() {
    this.getRolesData();
  },
  methods: {
    async getRolesData() {
      const { data: res } = await this.axios.get("roles");
      // console.log(res);
      if (res.meta.status == 200) {
        this.rolesData = res.data;
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    addVisibleClose() {
      this.$refs.addForm.resetFields();
    },
    addSure() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.axios.post("roles", this.addForm);
          console.log(res);
          if (res.meta.status == 201) {
            this.$message.success(res.meta.msg);
            this.addDialogVisible = false;
            this.getRolesData();
          }
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    async findEditId(val) {
      this.editDialogVisible = true;
      const { data: res } = await this.axios.get(`roles/${val}`);
      if (res.meta.status == 200) {
        this.editForm = res.data;
      } else {
        return false;
      }
    },
    async editSure() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.axios.put(
            `roles/${this.editForm.roleId}`,
            this.editForm
          );
          if (res.meta.status == 200) {
            this.editForm = res.data;
            this.editDialogVisible = false;
            this.$message.success("修改成功");
            this.getRolesData();
          } else {
            return false;
          }
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    async del(val) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res == "confirm") {
        const { data: res } = await this.axios.delete(`roles/${val}`);
        if (res.meta.status == 200) {
          this.$message.success(res.meta.msg);
          this.getRolesData();
        } else {
          this.$message.error(res.meta.msg);
        }
      } else if (res == "cancel") {
        this.$message.info("已取消删除");
      }
    },
    async handleClose(role, rightId) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res == "confirm") {
        const { data } = await this.axios.delete(
          `roles/${role.id}/rights/${rightId}`
        );
        if (data.meta.status == 200) {
          this.$message.success(data.meta.msg);
          role.children = data.data;
        } else {
          this.$message.error(data.meta.msg);
        }
      } else if (res == "cancel") {
        this.$message.info("已取消删除");
      }
    },
    async addRights(role) {
      this.roleId = role.id;
      const { data: res } = await this.axios.get("/rights/tree");
      this.treeData = res.data;
      this.getDefKeys(role, this.defKeys);
      this.addRightsDialogVisible = true;
    },
    defaultProps() {},
    async addRightsSure() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.axios.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      // console.log(res);
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
      } else {
        this.$message.error(res.meta.msg);
      }
      this.getRolesData();
      this.addRightsDialogVisible = false;
    },
    // 递归
    getDefKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getDefKeys(item, arr));
    },
    closeAddRightsDialog() {
      this.defKeys = [];
    },
  },
};
</script>

<style scoped></style>
